package com.kly.cashmall.module.home.home_tab.tab_other;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author
 * @date 2018/1/18
 */
public class ItemObserver<T> implements ObserverInterface<T> {

  private Map<String, ObsRunnable<T>> runnableMap = new ConcurrentHashMap<>();
  private String key;

  ItemObserver(String key) {
    this.key = key;
  }

  @Override
  public void handleChange(T t) {
    if (runnableMap.isEmpty()) {
      clear();
      return;
    }
    for (ObsRunnable<T> runnable : runnableMap.values()) {
      if (runnable != null) {
        runnable.run(t);
      }
    }
  }

  @Override
  public void registerObserve(String code, ObsRunnable<T> runnable) {
    runnableMap.put(code, runnable);
  }

  @Override
  public void unregisterObserve(String code) {
    runnableMap.remove(code);
  }

  @Override
  public boolean isEmpty() {
    return runnableMap.isEmpty();
  }

  @Override
  public void clear() {
    ObserverFactory.removeObserver(key);
    key = null;
    runnableMap.clear();
  }
}
